from django.shortcuts import render
from rest_framework.views import APIView
from .Ser import *
from rest_framework.response import Response
# Create your views here.


# 老师注册接口
class TeacherV(APIView):
    def post(self,request):
        ser=TeacherSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"meg":"添加成功","code":200})
        else:
            print(ser.errors)
            return Response({"meg":"添加失败","code":20010})

    def get(self,request):
        data=Teacher.objects.all()
        data_ser=TeacherSer(data,many=True)
        return Response(data_ser.data)

class TeacherLoginV(APIView):
    def post(self,request):
        username=request.data.get("username")
        password=request.data.get("password")
        if username and password:
            teacher=Teacher.objects.filter(username=username,password=password).first(
            )
            if teacher:
                return Response({"code":200,"tid":teacher.id,"tname":teacher.username})
        else:
            return Response({"code":10010})







# 添加展示学生
class StuV(APIView):
    def post(self,request):
        ser=StuSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"meg":"添加成功","code":200})
        else:
            return Response({"meg":"添加失败","code":20010})

    def get(self,request):
        tid=request.GET.get("id")
        stu=Stu.objects.filter(teacher_id=tid).all()
        ser=StuSer(stu,many=True)
        return Response({"code":200,"list":ser.data})

    def put(self, request):
        id = request.GET.get('id')
        Stu.objects.filter(id=id).update(teacher_id='')
        return Response({"code": 200})


#添加展示学生
class StuM(APIView):
    def get(self,request):
        tid = request.GET.get('tid')
        if tid:
            stu = Stu.objects.filter(teacher_id=tid).all()
        else:
            #没绑定的所有学生
            stu = Stu.objects.filter(teacher_id__isnull=True).all()
        ser = StuSer(stu,many=True)
        return Response({"code":200,'list':ser.data})
    def put(self,request):
        #学生id
        id = request.GET.get('id')
        tid = request.GET.get('tid')
        if tid:
            #绑定
            Stu.objects.filter(id=id).update(teacher_id=tid)
        else:
            #解绑
            Stu.objects.filter(id=id).update(teacher_id='')
        return Response({"code":200})

